package com.jianye.recycdona.control.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jianye.recycdona.control.Apps;
import com.jianye.recycdona.control.bean.Carousel;
import com.jianye.recycdona.control.bean.RecyclerOrder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.jianye.recycdona.control.Apps.JSON;

public class OrderHttp {
    private static final OrderHttp reserveHttp=new OrderHttp();

    private final Gson gson=common.getGson();
    private List<RecyclerOrder.DataBean> oderDataList =new ArrayList<>();
    private List<Carousel.ContentBean> carouselList;
    public static  String codeStatus;

    private OrderHttp() {

    }

    public static OrderHttp getMyOkHttp() {
        return reserveHttp;
    }

    private    static final OkHttpClient client= common.getClient();


    public int  postOrder(String addressid, String orderNumber, String orderStatus, String orderinfo, String parentId, String placeTime, String reserveStatus, String reserveTime, String weight) throws ExecutionException, InterruptedException {
       OrderThread callableThread = new OrderThread(addressid,orderNumber,orderStatus,orderinfo,parentId,placeTime,reserveStatus,reserveTime,weight);

       FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return 200;
    }
    class OrderThread implements Callable {

        private String addressid;//地址id
        private String orderNumber;
        private String orderStatus;
        private String orderinfo;
        private String parentId;//用户id
        private String placeTime;
        private String reserveStatus;//预约状态
        private String reserveTime;
        private String weight;

        public OrderThread(String addressid, String orderNumber, String orderStatus, String orderinfo, String parentId, String placeTime, String reserveStatus, String reserveTime, String weight) {
            this.addressid = addressid;
            this.orderNumber = orderNumber;
            this.orderStatus = orderStatus;
            this.orderinfo = orderinfo;
            this.parentId = parentId;
            this.placeTime = placeTime;
            this.reserveStatus = reserveStatus;
            this.reserveTime = reserveTime;
            this.weight = weight;
        }


        @Override
        public Object call() throws Exception {

            System.out.println(Thread.currentThread().getName());

            try {
                //传的json
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("addressid",addressid);
                jsonObject.put("order_number",orderNumber);
                jsonObject.put("order_status",orderStatus);
                jsonObject.put("orderinfo",orderinfo);
                jsonObject.put("parent_id",parentId);
                jsonObject.put("weight",weight);
                jsonObject.put("place_time",placeTime);
                jsonObject.put("reserve_status",reserveStatus);
                jsonObject.put("reserve_time",reserveTime);


                String callStr = UserOkHttp.post(Apps.postOrderInfo, jsonObject.toString());
                JSONObject call_json = new JSONObject(callStr);
                final String code = call_json.getString("status");
                System.out.print(code + "-------------------------------code");

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }

            System.out.print("-------------------------------OK");
            return "ok";
        }

    }


    /**
     * Get 获取当前用户所有订单信息
     */
    public List<RecyclerOrder.DataBean> getOrderInfo(String paretId) throws ExecutionException, InterruptedException {
        GetOrderinfo callableThread = new GetOrderinfo(paretId);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return oderDataList;
    }

    class GetOrderinfo implements Callable {
        private String parentId;

        public GetOrderinfo(String parentId) {
            this.parentId = parentId;
        }

        @Override
        public Object call() throws Exception {

            //url拼接
            Log.e("url", "-------------------------------------->"+ Apps.getOrderInfo+ parentId);

            Request request = new Request.Builder()
                    .url(Apps.getOrderInfo+parentId)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象


            if (response.isSuccessful()) {

                try {

                    assert response.body() != null;
                    String msginfo = response.body().string();

                    Log.e("msg", "------------------------------------" + msginfo);
                    RecyclerOrder fromJson = gson.fromJson(msginfo, RecyclerOrder.class);

                    int listsize=fromJson.getData().size();
                    Log.d("Orderlistsize", "call: ----------------->"+listsize);

                    if (oderDataList!=null){
                        oderDataList.clear();
                    }

                 for (int i=0;i<listsize;i++){

                     oderDataList.add(
                             new RecyclerOrder.DataBean(
                              fromJson.getData().get(i).getAddressid(),
                              fromJson.getData().get(i).getId(),
                              fromJson.getData().get(i).getOrderNumber(),
                              fromJson.getData().get(i).getOrderStatus(),
                              fromJson.getData().get(i).getOrderinfo(),
                              fromJson.getData().get(i).getParentId(),
                              fromJson.getData().get(i).getPlaceTime(),
                              fromJson.getData().get(i).getReserveStatus(),
                              fromJson.getData().get(i).getReserveTime(),
                              fromJson.getData().get(i).getWeight()
                      ));
                    }
                    Log.d("listsize", "------------------------------>" + fromJson.getStatus() + fromJson.getMsg()+listsize);
                    codeStatus=fromJson.getStatus()+"";

                } catch (IOException | JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            return codeStatus;
        }
    }

/***
 * 修改订单状态
 */
public String updataOderStatus(String id,String orderStatus,String reserveStatus){

    UpdataOrderStatus callableThread = new UpdataOrderStatus(id,orderStatus,reserveStatus);
    FutureTask futureTask = new FutureTask<>(callableThread);
    new Thread(futureTask).start();
    try {
        System.out.println(futureTask.get());
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return codeStatus;
}

 class UpdataOrderStatus implements Callable {

            String id;
            String ReserveStatus; //预约状态
            String OrderStatus; //订单状态

        public UpdataOrderStatus(String id, String orderStatus, String reserveStatus) {
            this.id = id;
            ReserveStatus = reserveStatus;
            OrderStatus = orderStatus;
        }


        @Override
    public Object call() throws Exception {

            JSONObject object=new JSONObject();
            object.put("id",id);
            object.put("order_status",OrderStatus);
            object.put("reserve_status",ReserveStatus);

            String callStr = put(object.toString());
            JSONObject call_json = new JSONObject(callStr);
            codeStatus = call_json.getString("status");
            Log.e("UpdateInfocode", codeStatus + "-------------------------------code");

            System.out.println(Thread.currentThread().getName());

        return codeStatus;

    }
        public   String put(String json) throws IOException {

            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Apps.putOrderInfo)
                    .put(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                assert response.body() != null;
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }

        }

  }

    /**
     * 修改订单信息
     */

    public String putOderInfo(String id, String addressid, String orderAddressInfo, String reserveTime, String orderWeight){

        PutOrderInfo callableThread = new PutOrderInfo(id,addressid,orderAddressInfo,reserveTime,orderWeight);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        return codeStatus;
    }

    class PutOrderInfo implements Callable {

        String id;
        String orderAddressInfo;
        String reserveTime;
        String orderWeight;
        String addressid;

        public PutOrderInfo(String id, String addressid, String orderAddressInfo , String reserveTime , String orderWeight ) {
            this.id = id;
            this.orderAddressInfo = orderAddressInfo;
            this.reserveTime = reserveTime;
            this.orderWeight = orderWeight;
            this.addressid = addressid;
        }


        @Override
        public Object call() throws Exception {

            JSONObject object=new JSONObject();
            object.put("id",id);
            object.put("orderinfo",orderAddressInfo);
            object.put("addressid",addressid);
            object.put("reserve_time",reserveTime);
            object.put("weight",orderWeight);

            Log.d("Edit_Json", "-------------------->call: "+object.toString());
            String callStr = put(object.toString());
            JSONObject call_json = new JSONObject(callStr);
            codeStatus = call_json.getString("status");

            Log.e("PutInfocode",   "-------------------------------code"+callStr);

            System.out.println(Thread.currentThread().getName());

            return codeStatus;
        }

        public   String put(String json) throws IOException {

            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Apps.putOrderInfo)
                    .put(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                assert response.body() != null;
                return response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }

        }

    }




    /**
     * Get 获取当前轮播资源
     */
    public List<Carousel.ContentBean> getCarousel() throws ExecutionException, InterruptedException {
        carouselList=new ArrayList<>();
        CarouselHttp callableThread = new CarouselHttp();
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return carouselList;
    }

    class CarouselHttp implements Callable {

        @Override
        public Object call() throws Exception {


            Request request = new Request.Builder()
                    .url(Apps.getCarousel)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象

            if (response.isSuccessful()) {

                try {
                    assert response.body() != null;
                    String msginfo = response.body().string();

                    Carousel fromJson = gson.fromJson(msginfo, Carousel.class);
                    carouselList=fromJson.getContent();

                    int listsize=fromJson.getContent().size();
                    Log.d("Orderlistsize", "call: ----------------->"+listsize);



                } catch (IOException | JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            return 200;
        }
    }




}
